<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="./jquery-2.1.4.min.js"></script>
<script>
    var socket;

    function openSocket() {
        if (typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接,注意协议为ws
            var socketUrl = "ws://localhost:8080/imserver/" + $("#userId").val();
            console.log(socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                $("#msg").append(msg.data)
                console.log("websocket已打开");
            };
            //获得消息事件
            socket.onmessage = function (msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
                $("#msg").append("</br>")
                $("#msg").append(msg.data)
            };
            //关闭事件
            socket.onclose = function () {
                $("#msg").append("</br>")
                $("#msg").append(msg.data)
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                $("#msg").append("</br>")
                $("#msg").append(msg.data)
                console.log("websocket发生了错误");
            }
        }
    }

    function sendMessage() {
        if (typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
            socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
        }
    }
</script>
<body>
<div><label style="width: 40px;">userId：</label><input id="userId" name="userId" type="text" value="1"></div>
<div><label style="width: 40px;">toUserId：</label><input id="toUserId" name="toUserId" type="text" value="2"></div>
<div><label style="width: 40px;">消息内容：</label><input id="contentText" name="contentText" type="text" value="你好！webSocket"></div>
<div><label style="width: 40px;">操作：</label>
    <button onclick="openSocket()">开启socket</button>&nbsp;<button onclick="sendMessage()">发送消息</button>
</div>
<div id="msg"></div>
</body>

</html>